package com.xh.one2one.lesson.service.impl;

import com.aspose.slides.Collections.ArrayList;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.system.service.IDictionaryService;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.model.Question;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.one2one.lesson.bean.dto.LessonSummaryDetailDto;
import com.xh.one2one.lesson.bean.dto.OneWrongQuestionDto;
import com.xh.one2one.lesson.bean.dto.OneWrongStudentDto;
import com.xh.one2one.lesson.bean.request.LessonSummaryDetailsRequest;
import com.xh.one2one.lesson.model.LessonInfo;
import com.xh.one2one.lesson.model.LessonSummaryDetails;
import com.xh.one2one.lesson.dao.LessonSummaryDetailsMapper;
import com.xh.one2one.lesson.model.LessonTimes;
import com.xh.one2one.lesson.service.ILessonInfoService;
import com.xh.one2one.lesson.service.ILessonSummaryDetailsService;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.one2one.lesson.service.ILessonTimesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 教学总结详情 服务实现类
 * </p>
 *
 * @author TW
 * @since 2021-05-06
 */
@Service
public class LessonSummaryDetailsServiceImpl extends BaseServiceImpl<LessonSummaryDetailsMapper, LessonSummaryDetails> implements ILessonSummaryDetailsService {

   @Autowired
   private IQuestionService questionService;
   @Autowired
   private ILessonInfoService lessonInfoService;
   @Autowired
   private IDictionaryService dictionaryService;
   @Autowired
   private ILessonTimesService lessonTimesService;

    @Override
    public XhPage queryLessonSummaryDetailsPage(XhPage page, LessonSummaryDetailsRequest bean) {
        QueryWrapper qw=new QueryWrapper<LessonSummaryDetails>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page,qw);
    }

    @Override
    public XhPage queryWrongQuestionPage(XhPage page, LessonSummaryDetailsRequest bean) {
        XhPage<LessonSummaryDetails> xhPage = this.dao.selectQuestionPage(page, bean);
        List<LessonSummaryDetails> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return xhPage;
        }
        Map<String, Date> wrongMap = records.stream().collect(Collectors.toMap(LessonSummaryDetails::getQuestionId, LessonSummaryDetails::getCreateTime));
//        String[] questionIds = records.stream().map(LessonSummaryDetails::getQuestionId).toArray(String[]::new);
//        QuestionQueryRequest request = new QuestionQueryRequest();
//        request.setIds(questionIds);
        List<QuestionDto> queryQuestion = new ArrayList();
        for (int i = 0; i < records.size(); i++) {
            LessonSummaryDetails lessonSummaryDetails = records.get(i);
            String questionId = lessonSummaryDetails.getQuestionId();
            queryQuestion.add(questionService.getPracticeQuestion(questionId,null));
        }

        List<OneWrongQuestionDto> retList = new ArrayList();
        queryQuestion = queryQuestion.stream().filter(questionDto -> null != questionDto).collect(Collectors.toList());
        queryQuestion.forEach(question->{
            question.setCreateTime(wrongMap.get(question.getId()));
            OneWrongQuestionDto dto = new OneWrongQuestionDto();
            BeanUtils.copyProperties(question,dto);

            bean.setQuestionId(question.getId());
            Integer count = queryWrongCount(bean);
            dto.setErrorCount(count);
            retList.add(dto);
        });
        xhPage.setRecords(retList);
        return xhPage;
    }

    @Override
    public List queryLessonSummaryDetails(LessonSummaryDetailsRequest bean) {
        QueryWrapper qw=new QueryWrapper<LessonSummaryDetails>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return this.dao.selectList(qw);
    }

    @Override
    public Integer queryWrongCount(LessonSummaryDetailsRequest bean) {
        QueryWrapper qw=new QueryWrapper<LessonSummaryDetails>();
        //拼装条件
//        qw.select("distinct student_id");
        qw=prepareParams(bean, qw);



        List<LessonSummaryDetails> list = this.dao.selectList(qw);
        if(CollectionUtils.isEmpty(list)){
            return 0;
        }else{
            return list.size();
        }

    }

    @Override
    public List<OneWrongStudentDto> queryWrongStudentGroupByLessonId(LessonSummaryDetailsRequest bean) {
        List<OneWrongStudentDto> retList = new ArrayList();

        List<LessonSummaryDetails> list = queryLessonSummaryDetails(bean);
        if(CollectionUtils.isEmpty(list)){
            return retList;
        }
        Map<String, List<LessonSummaryDetails>> groupMap = list.stream().collect(Collectors.groupingBy(LessonSummaryDetails::getLessonThirdId));
        groupMap.keySet().forEach(key->{
            LessonInfo info = lessonInfoService.getByThirdId(key);
            OneWrongStudentDto dto = new OneWrongStudentDto();
            dto.setLessonThirdId(info.getThirdId());
            dto.setLessonName(info.getLessonName());
            dto.setStudents(groupMap.get(key));
            retList.add(dto);
        });
        return retList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSave(List<LessonSummaryDetailsRequest> beans) {
        LessonSummaryDetailsRequest lessonSummaryDetails = beans.get(0);
        LessonSummaryDetailsRequest request = new LessonSummaryDetailsRequest();
        Integer type = lessonSummaryDetails.getType();
        //上节课作业单独处理
        boolean isHomework = 3 == type;
        LessonSummaryDetails prewData = new LessonSummaryDetails();
        if(isHomework){
            String lessonTimeId = lessonSummaryDetails.getLessonTimeId();
            LessonTimes lessonTimes = lessonTimesService.getById(lessonTimeId);
            if(null == lessonTimes){
                LessonInfo lessonInfo = lessonInfoService.getById(lessonTimeId);
                request.setLessonThirdId(lessonInfo.getThirdId());
                prewData.setLessonId(lessonInfo.getLessonId());
                prewData.setLessonThirdId(lessonInfo.getThirdId());
            }else{
                request.setLessonThirdId(lessonTimes.getLessonThirdId());
                prewData.setLessonId(lessonTimes.getLessonId());
                prewData.setLessonThirdId(lessonTimes.getLessonThirdId());
                prewData.setIndexId(lessonTimes.getPlanId());
            }
        }else {
            request.setLessonThirdId(lessonSummaryDetails.getLessonThirdId());
        }
        request.setLessonType(lessonSummaryDetails.getLessonType());
        request.setStudentId(lessonSummaryDetails.getStudentId());
        request.setType(type);
        List<String> questionIds = beans.stream().map(LessonSummaryDetailsRequest::getQuestionId).collect(Collectors.toList());

        QueryWrapper qw=new QueryWrapper<LessonSummaryDetails>();
        //拼装条件
        qw=prepareParams(request, qw);
        qw.in("question_id",questionIds);
        this.deleteByCondition(qw);
        List<LessonSummaryDetails> saveList = new ArrayList();
        beans.forEach(detailsRequest ->{
            LessonSummaryDetails data = new LessonSummaryDetails();
            BeanUtils.copyProperties(detailsRequest,data);
            if(isHomework){
                data.setLessonId(prewData.getLessonId());
                data.setLessonThirdId(prewData.getLessonThirdId());
                data.setIndexId(prewData.getIndexId());
            }
            saveList.add(data);
        } );
        this.batchInsert(saveList);

    }

    @Override
    public List querySubjectForWrong(LessonSummaryDetailsRequest bean) {
        List<LessonSummaryDetails> list = queryLessonSummaryDetails(bean);
        if(CollectionUtils.isEmpty(list)){
            return Collections.EMPTY_LIST;
        }
        List<String> questionIds = list.stream().map(LessonSummaryDetails::getQuestionId).collect(Collectors.toList());
        QueryWrapper<Question> questionQueryWrapper = new QueryWrapper<>();
        questionQueryWrapper.in("id",questionIds);
        List<Question> questions = questionService.queryByCondition(questionQueryWrapper);
        List<String> subjectIds = questions.stream().filter(question -> StringUtils.isNotEmpty(question.getSubjectId())).map(Question::getSubjectId).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(subjectIds)){
            return Collections.EMPTY_LIST;
        }
        QueryWrapper<Dictionary> dictionaryQueryWrapper = new QueryWrapper<>();
        dictionaryQueryWrapper.eq("type_code","SUBJECT");
        dictionaryQueryWrapper.in("code",subjectIds);
        return dictionaryService.queryByCondition(dictionaryQueryWrapper);
    }

    public List querySummaryQuestion(LessonSummaryDetailsRequest bean) {
        List<LessonSummaryDetails> list = queryLessonSummaryDetails(bean);
        if(CollectionUtils.isEmpty(list)){
            return Collections.EMPTY_LIST;
        }
        List<QuestionDto> retList = new ArrayList();
        for (LessonSummaryDetails details : list) {
            String questionId = details.getQuestionId();
            if(StringUtils.isNotEmpty(bean.getSubjectId())){
                QueryWrapper<Question> questionQueryWrapper = new QueryWrapper<>();
                questionQueryWrapper.eq("subject_id",bean.getSubjectId());
                questionQueryWrapper.eq("id",questionId);
                List<Question> questions = questionService.queryByCondition(questionQueryWrapper);
                if(!CollectionUtils.isEmpty(questions)){
                    retList.add(questionService.getQuestion(questionId, null));
                }
            }else{
                retList.add(questionService.getQuestion(questionId, null));
            }
        }
        return retList;
    }

    @Override
    public List<LessonSummaryDetailDto> querySummaryDetailDtoQuestion(LessonSummaryDetailsRequest bean) {
        List<LessonSummaryDetails> list = queryLessonSummaryDetails(bean);
        if(CollectionUtils.isEmpty(list)){
            return Collections.EMPTY_LIST;
        }
        List<LessonSummaryDetailDto> retList = new ArrayList();
        for (LessonSummaryDetails details : list) {
            LessonSummaryDetailDto detailDto = new LessonSummaryDetailDto();
            detailDto.setType(details.getType());
            String questionId = details.getQuestionId();
            if(StringUtils.isNotEmpty(bean.getSubjectId())){
                QueryWrapper<Question> questionQueryWrapper = new QueryWrapper<>();
                questionQueryWrapper.eq("subject_id",bean.getSubjectId());
                questionQueryWrapper.eq("id",questionId);
                List<Question> questions = questionService.queryByCondition(questionQueryWrapper);
                if(!CollectionUtils.isEmpty(questions)){
                    detailDto.setQuestionDto(questionService.getQuestion(questionId, null));
                }
            }else{
                detailDto.setQuestionDto(questionService.getQuestion(questionId, null));
            }
            retList.add(detailDto);
        }
        return retList;
    }

    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(LessonSummaryDetailsRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        if(StringUtils.isNotEmpty(bean.getLessonId())){
            qw.eq("lesson_id",bean.getLessonId());
        }
        if(StringUtils.isNotEmpty(bean.getLessonThirdId())){
            qw.eq("lesson_third_id",bean.getLessonThirdId());
        }
        if(StringUtils.isNotEmpty(bean.getIndexId())){
            qw.eq("index_id",bean.getIndexId());
        }
        if(StringUtils.isNotEmpty(bean.getStudentId())){
            qw.eq("student_id",bean.getStudentId());
        }
        if(StringUtils.isNotEmpty(bean.getQuestionId())){
            qw.eq("question_id",bean.getQuestionId());
        }
        if(null != bean.getLessonType()){
            qw.eq("lesson_type",bean.getLessonType());
        }
        if(null != bean.getType()){
            qw.eq("type",bean.getType());
        }
        if(null != bean.getCorrect()){
            qw.eq("correct",bean.getCorrect());
        }
        if(!CollectionUtils.isEmpty(bean.getLessonThirdIds())){
            qw.in("lesson_third_id",bean.getLessonThirdIds());
        }
        if(!StringUtils.isNotEmpty(bean.getStudentId())){
            qw.eq("student_id",bean.getStudentId());
        }
        if(!CollectionUtils.isEmpty(bean.getStudentIds())){
            qw.in("student_id",bean.getStudentIds());
        }
        if(!StringUtils.isEmpty(bean.getStartDate())){
            qw.ge("create_time",bean.getStartDate()+" 00:00:00");
        }
        if(!StringUtils.isEmpty(bean.getEndDate())){
            qw.le("create_time",bean.getEndDate()+" 23:59:59");
        }
        if(null != bean.getGroupId()){
            if(1 == bean.getGroupId()){
                qw.groupBy("student_id");
            }
            if(2 == bean.getGroupId()){
                qw.groupBy("lesson_third_id");
            }
            if(3 == bean.getGroupId()){
                qw.groupBy("question_id");
            }
        }
//        if(null != bean.getGroupId()){
//            if(1 == bean.getGroupId()){
//                qw.groupBy("student_id");
//            }
//            if(2 == bean.getGroupId()){
//                qw.groupBy("lesson_id");
//            }
//            if(3 == bean.getGroupId()){
//                qw.groupBy("question_id");
//            }
//        }
        if(null != bean.getOrderType()){
            if(1 == bean.getOrderType()){
                qw.orderByDesc("create_time");
                qw.orderByAsc("question_id");
            }
        }
        return qw;
    }

    @Override
    public Integer selectQuestionCountByType(String lessonThirdId,Integer type) {
        return this.dao.selectQuestionCountByType(lessonThirdId,type);
    }
}
